package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        //2.1搜索
        basicQuery(params, request);
        //2.3根据地理坐标排序
        String location = params.getLocation();
        if (location != null && location.equals("")) {
            request.source().sort(SortBuilders
                    //根据地理坐标排序             字段名           坐标形式(坐标("经,纬"))
                    .geoDistanceSort("location", new GeoPoint(location))
                    //排序方式(ASC)
                    .order(SortOrder.ASC)
                    //单位(千米)
                    .unit(DistanceUnit.KILOMETERS));
        }
        //2.2分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        //3.发送请求，得到响应
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //4.解析响应
        return handleResponse(response);
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        Map<String, List<String>> resultMap = new HashMap<>();

        SearchRequest request = new SearchRequest("hotel");
        //构造查询条件
        basicQuery(params, request);
        request.source().size(0);
        //构造聚合条件
        buildAggregation(request);
        //3.发起请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        resultMap.put("品牌", getAggregationByName(response, "brandAgg"));
        resultMap.put("城市", getAggregationByName(response, "cityAgg"));
        resultMap.put("星级", getAggregationByName(response, "starNameAgg"));
        return resultMap;
    }

    @SneakyThrows
    @Override
    public List<String> listSuggestion(String prefix) {
        //1.创建查询
        SearchRequest request = new SearchRequest("hotel");
        ///2.构造DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
        ));
        //3.查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.解析
        CompletionSuggestion suggestion = response.getSuggest().getSuggestion("suggestion");
        ArrayList<String> suggestions = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
            suggestions.add(String.valueOf(option.getText()));
        }
        return suggestions;
    }

    @SneakyThrows
    @Override
    public void deleteById(Long id) {
        //1.准备request
        DeleteRequest deleteRequest = new DeleteRequest("hotel", id.toString());
        //2.发送请求
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    @SneakyThrows
    @Override
    public void insertOrUpdateById(Long id) {
        //0.根据id查询酒店数据
        Hotel hotel = getById(id);
        //转为es索引库匹配的类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //1.准备request
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2.准备DSL
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 根据聚合名称解析结果
     *
     * @param response        总结果
     * @param aggregationName 聚合名称
     * @return 结果
     */
    private List<String> getAggregationByName(SearchResponse response, String aggregationName) {
        ArrayList<String> list = new ArrayList<>();
        //4.解析结果 response已经是结果了，只需要根据json逐层解析
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggregationName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKey().toString());
        }
        return list;
    }

    /**
     * 聚合条件
     *
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand"));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city"));
        request.source().aggregation(AggregationBuilders.terms("starNameAgg").field("starName"));
    }

    /**
     * 构建查询条件
     *
     * @param params
     */
    private void basicQuery(RequestParams params, SearchRequest request) {
        // 构建 BoolQueryBuilder
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        //如果搜索条件是空的
        if (key == null || key.equals("")) {
            //查询所有
            //request.source().query(QueryBuilders.matchAllQuery());
            //关键字查询用boolQuery
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            //查询指定
            //request.source().query(QueryBuilders.matchQuery("all", key));
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //城市条件查询
        if (params.getCity() != null && !params.getCity().equals("")) {
            //filter不参与算分 termQuery追加条件
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //品牌条件查询
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            //filter不参与算分 termQuery追加条件
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //星级条件查询
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            //filter不参与算分 termQuery追加条件
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //价格条件查询
        if (params.getMinPrice() != null && params.getMaxPrice() != null && !params.getMinPrice().equals("") && !params.getMaxPrice().equals("")) {
            //filter不参与算分 rangeQuery范围查询
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                //相关性原始查询                 functionScore数组
                QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中一个functionScore元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //满足条件的参与算分控制                                                     //满足条件算分x10
                                QueryBuilders.termQuery("isAD", true), ScoreFunctionBuilders.weightFactorFunction(10))
                });
        request.source().query(functionScoreQueryBuilder);
    }

    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<HotelDoc> hotels = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            // 4.4.获取source
            String json = hit.getSourceAsString();
            // 4.5.反序列化，非高亮的
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 获取地理坐标排序距离值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            // 4.9.放入集合
            hotels.add(hotelDoc);
        }
        return new PageResult(total, hotels);
    }
}
